package exchange.core;

import java.util.logging.Logger;


import exchange.util.Order;

public class Deal {
	private static Logger log = Logger.getLogger(Deal.class.getName());

	public static boolean makeDeal(Order newOrder, Order another ) {
		float dealPrice = another.getPrice();
		int dealAmount;
		boolean isAnotherOrderIsEmpty=false;
		
		if (newOrder.getAmount() >= another.getAmount()){
			dealAmount = another.getAmount();
			newOrder.setAmount(newOrder.getAmount() - another.getAmount() );
			another.setAmount(0);
			isAnotherOrderIsEmpty=true;
		}else{
			dealAmount = newOrder.getAmount();
			another.setAmount( another.getAmount() - newOrder.getAmount() );
			newOrder.setAmount(0 );
		}
		
		makeReport(newOrder, another, dealPrice, dealAmount);
		
		return isAnotherOrderIsEmpty;
	}
	
	
	public static void makeReport(Order newOrder, Order another, float price, int amount) {

		String client1Message = 
				"MATCH;" + newOrder.getOrderId() + ";" +
				another.getClient().getName() + ";" + price + ";" + amount + ";" ;
		
		String client2Message = 
				"MATCH;" + another.getOrderId() + ";" +
				newOrder.getClient().getName() + ";" + price + ";" + amount + ";" ;
	
		Mail.send(newOrder.getClient().getAdress(), client1Message );
		Mail.send( another.getClient().getAdress(), client2Message );
		
		log.info(newOrder.getClient().getName() + ", id-" + newOrder.getOrderId() + 
				" Matched by " + another.getClient().getName() + 
				" ( price = " + price + ", amount = " + amount + " )" );
	}
	
}
